package com.myteam.fugaocrm.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.myteam.fugaocrm.modle.FgUser;
import com.myteam.fugaocrm.sqldb.mapper.FgStaffMapper;
import com.myteam.fugaocrm.sqldb.mapper.FgUserMapper;

@Service
public class RegisterServiceImpl implements BaseService {

	@Resource protected FgUserMapper fgUserMapper;
	@Resource protected FgStaffMapper fgStaffMapper;
	
	public String register(String username, String password, String password2, String realname, String mobile) {
		//校验
		Pattern pattern = null;
		Matcher matcher = null;
		
		pattern = Pattern.compile("^[A-Za-z0-9_]{6,20}$");
		matcher = pattern.matcher(username); 
		if(!matcher.matches()) {
			return "用户名格式不正确，请输入6-20位字符（数字，大写字母，小写字母）";
		}
		FgUser user = fgUserMapper.selectUserByUsername(username);
		if(user != null) {
			return "该用户已被注册，请修改用户名";
		}
		matcher = pattern.matcher(password);
		if(!matcher.matches()) {
			return "密码格式不正确，请输入6-20位字符（数字，大写字母，小写字母）";
		}
		if(!password.equals(password2)) {
			return "两次密码输入不一致";
		}
		pattern = Pattern.compile("^[\u0391-\uFFE5]+$");
		matcher = pattern.matcher(realname); 
		if(!matcher.matches()) {
			return "真实姓名请输入汉字";
		}
		pattern = Pattern.compile("^[1][0-9]{10}$");
		matcher = pattern.matcher(mobile); 
		if(!matcher.matches()) {
			return "手机号输入不正确";
		}
		
		//新增用户
		Date date = new Date();
		Map<String, Object> params = new HashMap<String,Object>();
		params.put("username", username);
		params.put("password", password);
		params.put("createdUsre", realname);
		params.put("createdDate", date);
		params.put("modifiedUser", realname);
		params.put("modifiedDate", date);
		fgUserMapper.inster(params);
		
		//新增员工
		params = new HashMap<String,Object>();
		user = fgUserMapper.selectUserByUsername(username);
		params.put("userId", user.getUserId());
		params.put("permission", 0);
		params.put("staffMobile", mobile);
		params.put("staffUame", realname);
		params.put("createdUsre", user.getCreatedUser());
		params.put("createdDate", date);
		params.put("modifiedUser", user.getModifiedUser());
		params.put("modifiedDate", date);
		fgStaffMapper.insert(params);
		
		return "";
	}
	
}
